var socket = undefined;
var requestId = 0;
var requestsAwaitingResponse = {};
const RequestDownloadFileSystem = 0;
var latestServerFileSystemCache = undefined;
function syncWait(e) {
  var t = Date.now();
  while (Date.now() - t < e) {}
}
function createWebsocketWithFallback(e) {
  var t = 0;
  while (t < 10) {
    try {
      return new WebSocket(e);
    } catch (e) {
      syncWait(1e3);
    }
    t++;
  }
  alert("network I/O error");
}
const workerHandler = {
  start: (e, t) => {
    var s = t.data[2];
    var a = t.data[3];
    socket = createWebsocketWithFallback(
      "ws://localhost:" + s.toString() + "/" + a + "/liveBackup"
    );
    socket.binaryType = "arraybuffer";
    socket.onopen = () => {
      cacheServerFileSystem();
    };
    socket.onmessage = (e) => {
      const t = new DataView(e.data);
      const s = t.getInt32(0, true);
      const a = t.getInt32(4, true);
      const r = e.data.slice(8);
      if (s === -1) {
      } else {
        var n = requestsAwaitingResponse[s];
        if (n) {
          delete requestsAwaitingResponse[s];
          n(a, r);
        }
      }
    };
    postMessage([e]);
  },
  getLatestCached: (e, t) => {
    if (latestServerFileSystemCache) {
      bufferToBase64Async(latestServerFileSystemCache, (t) => {
        postMessage([e, t]);
      });
    } else {
      postMessage([e, ""]);
    }
  },
  updateCacheNow: (e, t) => {
    cacheServerFileSystemNow(() => {
      postMessage([e, ""]);
    });
  },
  cachedIsStale: (e, t) => {
    latestServerFileSystemCache = undefined;
    postMessage([e]);
  },
};
onmessage = (e) => {
  var t = e.data[0];
  var s = e.data[1];
  workerHandler[s](t, e);
};
function request0(e, t) {
  requestId++;
  var s;
  const a = 5;
  s = new Uint8Array([
    e,
    requestId & 255,
    (requestId >> 8) & 255,
    (requestId >> 16) & 255,
    (requestId >> 24) & 255,
  ]);
  if (t) requestsAwaitingResponse[requestId] = t;
  socket.send(s);
}
function cacheServerFileSystemNow(e) {
  var t = performance.now();
  request0(RequestDownloadFileSystem, (s, a) => {
    latestServerFileSystemCache = a;
    var r = performance.now() - t;
    console.log("got the live-backup response: " + a.byteLength + " in " + r);
    e();
  });
}
function cacheServerFileSystem() {
  cacheServerFileSystemNow(() => {
    setTimeout(cacheServerFileSystem, 6e4);
  });
}
function bufferToBase64Async(e, t) {
  var s = new Blob([e], { type: "application/octet-binary" });
  var a = new FileReader();
  a.onload = function () {
    var e = a.result;
    var s = e.substr(e.indexOf(",") + 1);
    t(s);
  };
  a.readAsDataURL(s);
}
